package liuliu.throughwaring.ui.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;

import net.tsz.afinal.annotation.view.CodeNote;

import liuliu.custom.control.dialog.LLDialog;
import liuliu.custom.control.edittext.ImageEditText;
import liuliu.custom.control.edittext.SpinnerEditText;
import liuliu.custom.control.picker.DatePickerDialog;
import liuliu.custom.control.toolbar.TToolbar;
import liuliu.custom.method.Utils;
import liuliu.throughwaring.R;
import liuliu.throughwaring.adapter.CommonAdapter;
import liuliu.throughwaring.adapter.ViewHolder;
import liuliu.throughwaring.base.BaseActivity;

import com.ivsign.android.IDCReader.Cvr100bMYTask;
import com.ivsign.android.IDCReader.Cvr100bTask;
import com.ivsign.android.IDCReader.IdcardInfoExtractor;
import com.ivsign.android.IDCReader.IdcardValidator;

import java.io.File;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import liuliu.throughwaring.control.add.police.person.IRegPersonView;
import liuliu.throughwaring.control.add.police.person.RegPersonListener;
import liuliu.throughwaring.model.AlarmModel;
import liuliu.throughwaring.model.BlueToothModel;
import liuliu.throughwaring.model.CodeModel;
import liuliu.throughwaring.model.CompanyModel;
import liuliu.throughwaring.model.NationAlarmModel;
import liuliu.throughwaring.model.PersonModel;

/**
 * Created by liuliu on 2015/11/19   9:25
 * 注册人员信息
 *
 * @author 柳伟杰
 * @Email 1031066280@qq.com
 */
public class RegPersonActivity extends BaseActivity implements IRegPersonView {
    public static RegPersonActivity mInstance;
    @CodeNote(id = R.id.reg_person_toolbar)
    TToolbar mToolbar;
    @CodeNote(id = R.id.reg_person_image, click = "onClick")
    ImageView img_iv;//
    @CodeNote(id = R.id.reg_person_user_nation, click = "onClick")
    SpinnerEditText reg_person_user_nation;//民族
    @CodeNote(id = R.id.reg_person_entry_time, click = "onClick")
    SpinnerEditText entry_time_txt;//入职时间
    @CodeNote(id = R.id.reg_person_entry_timestart, click = "onClick")
    SpinnerEditText entry_time_txtstart;//起租时间
    @CodeNote(id = R.id.reg_person_entry_timeend, click = "onClick")
    SpinnerEditText entry_time_txtend;//退租时间
    @CodeNote(id = R.id.reg_person_operating_pancha, click = "onClick")
    ImageEditText txtpancha;//盘查原因
    @CodeNote(id = R.id.reg_person_name)
    ImageEditText user_name_txt;//人员姓名
    @CodeNote(id = R.id.reg_person_idcard)
    ImageEditText idcard_txt;//身份证号(15位或者18位)
    @CodeNote(id = R.id.reg_person_tel)
    ImageEditText tel_txt;//联系电话
    @CodeNote(id = R.id.reg_person_user_address)
    ImageEditText user_address_txt;//地址
    @CodeNote(id = R.id.reg_person_user_station)
    ImageEditText user_station_txt;//职务
    @CodeNote(id = R.id.reg_person_operating_post)
    ImageEditText operating_post_txt;//工作岗位
    @CodeNote(id = R.id.reg_person_remark)
    ImageEditText remark_txt;//备注
    @CodeNote(id = R.id.reg_person_read_btn, click = "onClick")
    Button read_btn;//读卡
    @CodeNote(id = R.id.reg_person_save_btn, click = "onClick")
    Button save_btn;//保存
    PersonModel personModel;
    //右侧菜单
    @CodeNote(id = R.id.reg_person_right_menu_draw)
    DrawerLayout right_menu;//右侧菜单
    @CodeNote(id = R.id.right_menu_police_search_ll)
    LinearLayout right_menu_police_search_ll;
    @CodeNote(id = R.id.right_menu_unit_search_ll)
    LinearLayout right_menu_unit_search_ll;
    @CodeNote(id = R.id.right_menu_person_search_ll)
    LinearLayout right_menu_person_search_ll;
    @CodeNote(id = R.id.right_menu_toolbar)
    TToolbar toolbar;
    @CodeNote(id = R.id.right_menu_search_button)
    Button right_button;
    @CodeNote(id = R.id.right_menu_listview)
    ListView mRightMenu;
    List<CodeModel> mCodeListNation;
    List<CodeModel> mCodeListCardType;
    List<CodeModel> mCodeListNative;
    List<CodeModel> mCodeListSex;
    DatePickerDialog datePickerDialog;
    RegPersonListener mListener;
    StringBuffer path = new StringBuffer();
    Bitmap bm = null;
    String transactionId = "0";
    CompanyModel companyModel;
    String companyName = "";//用来接收传递过来的企业信息
    private LLDialog llDialog;

    @Override
    public void initViews() {
        setContentView(R.layout.activity_reg_person);
        mInstance = this;
        Utils.ReadString("NowLocation");
        llDialog = new LLDialog(this);
        companyName = getIntent().getStringExtra("companyName");
        transactionId = getIntent().getStringExtra("TransactionId");
        //获得当前的企业信息并存储在Model中
        if (!("").equals(companyName)) {
            if (companyName.equals("liudong")) {
                companyName = "流动人员单位";
            } else {
                companyName = companyName.split(":")[1];
            }
            companyModel = finalDb.findAllByWhere(CompanyModel.class, "CompanyName='" + companyName + "'").get(0);
        }
        personModel = new PersonModel();
        mListener = new RegPersonListener(this, this);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String nowTime = formatter.format(curDate);
        switch (companyModel.getCompanyType()) {
            case "Company"://从业人员
                mToolbar.setCenterTitle("从业人员添加");
                entry_time_txt.setVisibility(View.VISIBLE);
                user_station_txt.setVisibility(View.VISIBLE);
                operating_post_txt.setVisibility(View.VISIBLE);
                entry_time_txt.setCenterTxt(nowTime);
                txtpancha.setVisibility(View.GONE);
                entry_time_txtend.setVisibility(View.GONE);
                entry_time_txtstart.setVisibility(View.GONE);
                break;
            case "Free"://流动人员
                mToolbar.setCenterTitle("流动人员添加");
                txtpancha.setVisibility(View.VISIBLE);
                entry_time_txt.setVisibility(View.GONE);
                user_station_txt.setVisibility(View.GONE);
                operating_post_txt.setVisibility(View.GONE);
                entry_time_txtend.setVisibility(View.GONE);
                entry_time_txtstart.setVisibility(View.GONE);
                break;
            case "Lease"://租赁人员
                mToolbar.setCenterTitle("租赁人员添加");
                entry_time_txtend.setVisibility(View.VISIBLE);
                entry_time_txtstart.setVisibility(View.VISIBLE);
                entry_time_txt.setCenterTxt(nowTime);
                entry_time_txtstart.setCenterTxt(nowTime);
                txtpancha.setVisibility(View.GONE);
                entry_time_txt.setVisibility(View.GONE);
                user_station_txt.setVisibility(View.GONE);
                operating_post_txt.setVisibility(View.GONE);
                break;
        }
        initDatas();
    }

    @Override
    public void initEvents() {
        mToolbar.setLeftOnClick(new TToolbar.LeftOnClickListener() {
            @Override
            public void leftclick() {
                mInstance.finish();
            }
        });
        toolbar.setLeftOnClick(new TToolbar.LeftOnClickListener() {
            @Override
            public void leftclick() {
                drawerManager(1);
            }
        });
        mRightMenu.setVisibility(View.VISIBLE);
        right_menu_unit_search_ll.setVisibility(View.GONE);
        right_menu_person_search_ll.setVisibility(View.GONE);
        right_menu_police_search_ll.setVisibility(View.GONE);
        right_button.setVisibility(View.GONE);
    }

    private void refushRightMenu(final int type) {
        List<CodeModel> mCode = new ArrayList<>();
        switch (type) {
            case 1://性别
                mCode = mCodeListSex;
                break;
            case 2://民族
                mCode = mCodeListNation;
                break;
            case 3://证件类型
                mCode = mCodeListCardType;
                break;
            case 4://籍贯
//                mCode = mCodeListNative;

                break;
        }
        //左划菜单的Adapter
        mRightMenu.setAdapter(new CommonAdapter<CodeModel>(mInstance, mCode,
                R.layout.right_menu_item) {
            @Override
            public void convert(final ViewHolder holder, final CodeModel model, int position) {
                if (model.getValue() != null) {
                    holder.setText(R.id.right_menu_title, model.getValue());
                }
            }
        });

        //左划菜单项点击事件
        mRightMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                drawerManager(type);
                switch (type) {
                    case 2://民族
                        reg_person_user_nation.setCenterTxt(mCodeListNation.get(position).getValue());
                        break;
                }
            }
        });
        //设置高度
        setListViewHeightBasedOnChildren(mRightMenu);
    }

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        //获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) { //listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); //计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight() + listView.getDividerHeight() / 2; //统计所有子项+dividerheight的总高度
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() + 2)) + 20;
        //listView.getDividerHeight()获取子项间分隔符占用的高度
        //params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    //加载数据
    private void initDatas() {
        mCodeListNation = new ArrayList<>();
        mCodeListNation = finalDb.findAllByWhere(CodeModel.class, "codeName='Code_Nation'");
        mCodeListCardType = finalDb.findAllByWhere(CodeModel.class, "codeName='Code_CardType'");
        mCodeListNative = finalDb.findAllByWhere(CodeModel.class, "codeName='Code_Native'");
        mCodeListSex = finalDb.findAllByWhere(CodeModel.class, "codeName='Code_Sex'");
        personModel.setPersonSex("1");
        personModel.setPersonNation("01");
        personModel.setPersonNative("110000");
        personModel.setPersonCardType("11");
        reg_person_user_nation.setCenterTxt("汉族");
        idcard_txt.AddChangeMethod(new EditChangedListener());
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.reg_person_user_nation://民族
                refushRightMenu(2);
                drawerManager(2);
                break;
            case R.id.reg_person_image:
                startCamera(11);
                break;
            case R.id.reg_person_read_btn://读取身份证
                if (Utils.ReadString("BlueToothAddress").equals("")) {
                    Utils.ToastShort(RegPersonActivity.this, "请检查蓝牙读卡设备设置！");
                    mUtils.IntentPost(SysSettingActivity.class);//跳转登录
                } else {
                    onReadCardCvr();
                }
                break;
            case R.id.reg_person_entry_time:
                datePickerDialog = new DatePickerDialog(mInstance, "");
                datePickerDialog.datePickerDialog(entry_time_txt);
                break;
            case R.id.reg_person_save_btn:
                personModel = new PersonModel();
                if (!checkCardId()) {
                    Utils.ToastShort(RegPersonActivity.this, "身份证号码错误");
                } else {
                    if (checkPersonSave()) {
                        List<NationAlarmModel> list = finalDb.findAllByWhere(NationAlarmModel.class, "IdentntyNumber='" + mUtils.stringToSha1(idcard_txt.getText()).toUpperCase() + "'");
                        if (list != null) {
                            if (list.size() > 0) {
                                llDialog.setMiddleMessage("此人为“全国在逃人员”，请采取措施！！！ ");
                                llDialog.setOnPositiveListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        getPersonModel();
                                        mListener.RegPerson(personModel);
                                        llDialog.dismiss();
                                    }
                                });
                                llDialog.show();
                            }
                        } else {
                            getPersonModel();
                            mListener.RegPerson(personModel);
                        }
                    }
                }
                break;
            case R.id.reg_person_entry_timeend:
                datePickerDialog = new DatePickerDialog(mInstance, "");
                datePickerDialog.datePickerDialog(entry_time_txtend);
                break;
            case R.id.reg_person_entry_timestart:
                datePickerDialog = new DatePickerDialog(mInstance, "");
                datePickerDialog.datePickerDialog(entry_time_txtstart);
                break;
        }
    }

    /*开启关闭左划菜单*/
    private void drawerManager(int i) {
        if (right_menu.isDrawerOpen(GravityCompat.END)) {
            right_menu.closeDrawer(GravityCompat.END);
        } else {
            right_menu.openDrawer(GravityCompat.END);
            String title = "选择性别";
            switch (i) {
                case 1:
                    title = "选择性别";
                    break;
                case 2:
                    title = "民族";
                    break;
                case 3:
                    title = "人员类型";
                    break;
                case 4:
                    title = "籍贯";
                    break;
            }
            toolbar.setCenterTitle(title);
        }
    }

    //cvr
    private void onReadCardCvr() {
        if (Utils.checkBluetooth(RegPersonActivity.this, 2)) {
            final ProgressDialog progressDialog = ProgressDialog.show(RegPersonActivity.this, "", "正在读取身份证信息...", true, true);
            final Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    Bundle bundle = msg.getData();
                    boolean find = false;
                    progressDialog.dismiss();
                    if (bundle != null) {
                        boolean result = bundle.getBoolean("result");
                        PersonModel person = (PersonModel) bundle.getSerializable("person_info");
                        if (result) {
                            find = true;
                            setPerson(person);
                        } else {
                            Utils.ToastShort(RegPersonActivity.this, person.getPersonName());
                        }
                    }
                    if (!find) {
                        Utils.ToastShort(RegPersonActivity.this, "证件读取失败！（cvr）");
                    }
                }
            };

            new Cvr100bMYTask().startCvr100bTask(mInstance, new Cvr100bTask.Cvr100bListener() {
                @Override
                public BlueToothModel reauestBlueDevice() {
                    BlueToothModel blue = new BlueToothModel();
                    blue.setDeviceAddress(Utils.ReadString("BlueToothAddress"));
                    return blue;
                }

                @Override
                public void onResult(boolean result, PersonModel person) {
                    Message msg = handler.obtainMessage(1);
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("result", result);
                    bundle.putSerializable("person_info", person);
                    msg.setData(bundle);
                    msg.sendToTarget();
                }
            });
        } else {
            Utils.ToastShort(RegPersonActivity.this, "请检查蓝牙读卡设备设置！");
        }
    }

    private String getCodeVlaue(List<CodeModel> list, String name) {
        for (CodeModel c : list) {
            if (c.getName().equals(name)) {
                return c.getValue();
            }
        }
        return "";
    }

    private String getCodeName(List<CodeModel> list, String value) {
        for (CodeModel c : list) {
            if (c.getValue().equals(value)) {
                return c.getName();
            }
        }
        return "";
    }

    private void setPerson(PersonModel person) {
        idcard_txt.setText(person.getPersonCardId());
        user_name_txt.setText(person.getPersonName());
        user_address_txt.setText(person.getPersonAddress());
        if (person.getPersonCardImage() != null) {
            if (!person.getPersonCardImage().equals("")) {
                img_iv.setImageBitmap(Utils.getBitmapByte(person.getPersonCardImage()));
            }
        } else {
            Utils.ToastShort(RegPersonActivity.this, "照片解码失败！");
        }
        //民族
        reg_person_user_nation.setCenterTxt(getCodeVlaue(mCodeListNation, person.getPersonNation()));
    }

    private String sexid = "";//性别编码
    private String nativeid = "";//籍贯编码

    private void getPersonModel() {
        personModel.setPersonCardType("11");
        personModel.setPersonNation(getCodeName(mCodeListNation, reg_person_user_nation.getCenterText()));
        personModel.setPersonSex(sexid);
        personModel.setPersonAddress(user_address_txt.getText());
        personModel.setPersonCardId(idcard_txt.getText());
        personModel.setPersonCompanyId(companyModel.getCompanyId());
        personModel.setPersonComapnyName(companyModel.getCompanyName());
        personModel.setPersonComapnyType(companyModel.getCompanyType());
        personModel.setPersonComment(remark_txt.getText());
        personModel.setPersonTransactionId(transactionId);
        personModel.setPersonPoliceId(Utils.ReadString("PoliceId"));
        personModel.setPersonPhoneNumber(tel_txt.getText());
        personModel.setPersonId("");
        personModel.setPersonNative(nativeid);

        personModel.setJob(operating_post_txt.getText());

        personModel.setCheckReason(txtpancha.getText());
        if (companyModel.getCompanyType().equals("Company")) {
            personModel.setCheckInTime(Utils.changDatetoGeshi(entry_time_txt.getCenterText()));
            personModel.setPersonStatus("OnJob");
        } else if (companyModel.getCompanyType().equals("Lease")) {
            personModel.setPersonStatus("CheckIn");
            personModel.setCheckOutTime(entry_time_txtend.getCenterText());
            personModel.setCheckInTime(entry_time_txtstart.getCenterText());
        } else {
            personModel.setPersonStatus("None");
        }
        //Utils.changDatetoGeshi(entry_time_txt.getCenterText())
        personModel.setOffice(user_station_txt.getText());
        personModel.setPersonName(user_name_txt.getText().trim());
        if (bm != null) {
            personModel.setPersonCardImage(Utils.encodeBitmap(bm));
        } else {
            personModel.setPersonCardImage("");
        }
    }

    private boolean checkPersonSave() {
        if (user_name_txt.getText().equals("")) {
            mUtils.ToastShort("姓名不能为空");
            return false;
        } else if (tel_txt.getText().equals("")) {
            mUtils.ToastShort("电话不能为空");
            return false;
        } else if (idcard_txt.getText().equals("")) {
            mUtils.ToastShort("证件号码不能为空");
            return false;
        } else {
            switch (companyModel.getCompanyType()) {
                case "Company":
                    if (user_station_txt.getText().equals("")) {
                        mUtils.ToastShort("职务不能为空");
                        return false;
                    }
                    if (user_address_txt.getText().equals("")) {
                        mUtils.ToastShort("人员住址不能为空");
                        return false;
                    }
                    if (operating_post_txt.getText().equals("")) {
                        mUtils.ToastShort("工作岗位不能为空");
                        return false;
                    }
                    break;
                case "Free":
                    if (txtpancha.getText().equals("")) {
                        mUtils.ToastShort("盘查原因不能为空");
                        return false;
                    }
                    // txtpancha.setText("");
                    break;
//                case "Lease":
//                    entry_time_txtend.setCenterTxt("");
//                    entry_time_txtstart.setCenterTxt("");
//                    break;
            }
            return true;
        }
    }

    @Override
    public void onRegPersonResult(boolean isTrue, String mes) {
        if (isTrue) {
            finalDb.save(new AlarmModel(mes, Utils.ReadString("PoliceId"), Utils.getRealTime()));
            Intent intent = new Intent();
            Bundle b = new Bundle();
            b.putSerializable("PersonModel", personModel);
            intent.putExtras(b);
            this.setResult(131, intent);//返回页面1
            this.finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 12 && resultCode == 12) {
            String name = data.getStringExtra("CodeAreaName");
            String value = data.getStringExtra("CodeAreaValue");
//            reg_person_user_native.setCenterTxt(value);
            personModel.setPersonNative(name);
        }
        if (requestCode == 11) {
            bm = Utils.getimage(this, path.toString());
            if (bm != null) {
                img_iv.setImageBitmap(bm);
                img_iv.setTag(bm);
            } else {
                img_iv.setImageResource(R.mipmap.person_header);
                img_iv.setTag(bm);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //开启拍照
    public void startCamera(int type) {
        // 利用系统自带的相机应用:拍照
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        path = new StringBuffer();
        path.append(RegPersonActivity.this.getExternalFilesDir(null)).append("/IMG_CASH.jpg");
        File file = new File(path.toString());
        Uri uri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, type);
    }

    private boolean checkCardId() {
        boolean result = false;
        try {
            String card_id = idcard_txt.getText().toString();
            if (!Utils.isEmptyString(card_id)) {
                IdcardValidator iv = new IdcardValidator();
                if (!iv.isValidatedAllIdcard(card_id)) {
                    idcard_txt.setCenterTextRedColor();
                } else {
                    IdcardInfoExtractor iie = new IdcardInfoExtractor(card_id);
                    sexid = iie.getGender();
                    nativeid = iie.getNativeCode();
                    personModel.setPersonBirthday(String.format("%04d-%02d-%02d",
                            iie.getYear(), iie.getMonth(), iie.getDay()));
                    result = true;
                    idcard_txt.setCenterTextRedColor2();
                }
            }
        } catch (Exception e) {
            idcard_txt.setCenterTextRedColor();
            result = false;
        }
        return result;
    }

    class EditChangedListener implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            checkCardId();
        }
    }

    private void ClearText() {
        personModel = new PersonModel();
        user_name_txt.setText("");
        personModel.setPersonSex("1");
        personModel.setPersonNation("01");
        personModel.setPersonNative("110000");
        personModel.setPersonCardType("11");
        reg_person_user_nation.setCenterTxt("汉族");
        tel_txt.setText("");
        idcard_txt.setText("");
        user_address_txt.setText("");
        remark_txt.setText("");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String nowTime = formatter.format(curDate);
        switch (companyModel.getCompanyType()) {
            case "Company":
                entry_time_txt.setCenterTxt(nowTime);
                user_station_txt.setText("");
                operating_post_txt.setText("");
                break;
            case "Free":
                txtpancha.setText("");
                break;
            case "Lease":
                entry_time_txtend.setCenterTxt(nowTime);
                entry_time_txtstart.setCenterTxt(nowTime);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bm != null) {
            if (!bm.isRecycled()) {
                bm.recycle();//回收图片所占的内存
                System.gc();
            }
        }
    }
}
